import net from 'net'
import { createServer } from 'vite'

async function isFree(port) {
  return await new Promise((resolve) => {
    const srv = net.createServer()
    srv.once('error', () => resolve(false))
    srv.once('listening', () => srv.close(() => resolve(true)))
    srv.listen(port, '0.0.0.0')
  })
}

async function findPort(start, tries = 20) {
  for (let p = start; p < start + tries; p++) {
    if (await isFree(p)) return p
  }
  return start
}

const basePort = Number(process.env.PORT || process.env.VITE_PORT || 5173)
const port = await findPort(basePort)

const server = await createServer({ server: { port, strictPort: true, host: true } })
await server.listen()
server.printUrls()